package com.easpeed.comon.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PointF
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout

class BatteryView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet?,
) : View(context, attrs) {

    private var batteryLevel = 100 // 电量百分比 [0-100]

    private val paint = Paint().apply {
        isAntiAlias = true
        style = Paint.Style.FILL
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val offset = 1.5f
        // 电池正极参数
        val capWidth = 3f
        val capHeight = height / 2.5f

        // 电池主体参数
        val batteryWidth = width - capWidth - offset
        val batteryHeight = height - offset


        val batteryLeft = offset
        val batteryTop = offset
        val batteryRight = batteryWidth * 1f
        val batteryBottom = batteryHeight * 1f


        val capLeft = batteryRight
        val capTop = batteryTop + (batteryHeight - capHeight) / 2f
        val capRight = width * 1f
        val capBottom = capTop + capHeight

        // 绘制电池主体 (空心圆角矩形)
        paint.style = Paint.Style.STROKE
        paint.color = Color.BLACK
        paint.strokeWidth = 3f
        canvas.drawRoundRect(batteryLeft, batteryTop, batteryRight, batteryBottom, 5f, 5f, paint)


        // 绘制电池正极 (矩形)
        paint.style = Paint.Style.FILL
        canvas.drawRoundRect(capLeft, capTop, capRight, capBottom,6f,6f, paint)

        // 计算电量高度
        val levelWidth = (batteryWidth - 8) * (batteryLevel / 100f)
        val levelLeft = batteryLeft + 3
        val levelRight = levelLeft + levelWidth
        val levelTop = batteryTop + 3
        val levelBottom = batteryBottom - 3

        // 设置电量颜色 (绿色：高，黄色：中，红色：低)
//        paint.color = when {
//            batteryLevel > 50 -> Color.GREEN
//            batteryLevel > 20 -> Color.YELLOW
//            else -> Color.RED
//        }

        // 绘制电量部分
        canvas.drawRoundRect(levelLeft, levelTop, levelRight, levelBottom, 6f, 6f,paint)
    }

    // 更新电量并重绘
    fun setBatteryLevel(level: Int) {
        batteryLevel = level.coerceIn(0, 100) // 确保电量在 [0, 100]
        invalidate()
    }


}
